<?php

namespace App\Models;

use Auth;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class GroupBuyData extends BaseModel
{

    protected $appends = ['members', 'isJoin'];

    protected $casts = [
        'member_ids' => 'json'
    ];

    public function getMembersAttribute($value): Collection
    {
        $memberIds = $this->member_ids ?? [];
        return \DB::table('user')->select(['id', 'nickname', 'avatar'])->whereIn('id', $memberIds)->get();
    }

    public function getIsJoinAttribute(): bool
    {
        if (Auth::guard('api')->check()) {
            if ($this->leader_id == Auth::guard('api')->user()->id) return true;

            $_memberIds = $this->member_ids ?? [];
            if (in_array(Auth::guard('api')->user()->id, $_memberIds)) return true;
        }

        return false;
    }
}
